import java.io.*;
import java.net.Socket;

public class TCPCopyPictureClient {
    public static void main(String[] args) {
        try {
            Socket client = new Socket("127.0.0.1", 8888);

            // step0 打开输入输出流
            InputStream inputStream = client.getInputStream();
            // 将字节流转为字符流
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
            // 打开输入缓冲区
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

            OutputStream outputStream = client.getOutputStream();
            OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream);
            BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter);

            String fileName = bufferedReader.readLine();
            System.out.println("文件名称：" + fileName);
            long size = Long.parseLong(bufferedReader.readLine());
            System.out.println("文件大小：" + size);

            FileOutputStream fileOutputStream = new FileOutputStream("copy " + fileName);
            byte[] bytes = new byte[8192];
            int length;
            long tempSize = 0;
            while ((length = inputStream.read(bytes)) != -1) {
                fileOutputStream.write(bytes, 0 , length);
                tempSize += length;
                if (tempSize == size){
                    break;
                }
            }
            fileOutputStream.close();


            String info = "图片接收完成";
            bufferedWriter.write(info);
            bufferedWriter.write("\r\n");
            bufferedWriter.flush();

            // step 关闭输入输出流 socket
            bufferedReader.close();
            inputStreamReader.close();
            inputStream.close();

            bufferedWriter.close();
            outputStreamWriter.close();
            outputStream.close();

            client.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
